﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a catalog supplier comment.
    /// </summary>
    public class CreateCatalogSupplierComment : CreateComment<CatalogSupplierCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) => ctx.Account(uow).EntityID == AccountID);
                yield return new SecurityPolicy()
                    .Rule((ctx, uow) => AccountID == 0);
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CatalogSupplierCommentFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            var supplier = uow.Execute(new GetCatalogSupplier
            {
                ThrowsException = true,
                EntityID = HolderID
            }).Result;
            if(!supplier.Flags.HasFlag(CatalogSupplierFlags.CommentAllowed))
                return Err.Of(this).NotAllowed();
            if(!uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Catalog").Of<CatalogSupplierCommentEntity>().Name("Allowed")
            }).ResultAs<Boolean>())
            {
                return Err.Of(this).NotAllowed();
            }

            var account = AccountID == 0 ? null : uow.Execute(new GetAccount
            {
                ThrowsException = true,
                EntityID = AccountID
            }).Result;
            if(account == null)
            {
                if(!supplier.Flags.HasFlag(CatalogSupplierFlags.AnonCommentAllowed))
                    return Err.Of(this).NotAllowed().Reason("Anon");
                if(!uow.Execute(new GetConfigParamValueByKey
                {
                    Key = Par.In("Catalog").Of<CatalogSupplierCommentEntity>().Name("AnonAllowed")
                }).ResultAs<Boolean>())
                {
                    return Err.Of(this).NotAllowed().Reason("Anon");
                }
            }

            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out CatalogSupplierCommentEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdateCatalogSupplierStats
            {
                EntityID = result.HolderID
            });

            foreach(var i in uow.Execute(new GetCatalogSupplier
            {
                ThrowsException = true,
                EntityID = result.HolderID
            }).Result.Managers)
            {
                try
                {
                    uow.Execute(new EnqueueCatalogSupplierCommentNotification
                    {
                        CommentID = result.EntityID,
                        RecipientID = i.Account.EntityID
                    });
                }
                catch(Exception ex)
                {
                    uow.Execute(new CreateLogRecordFromException
                    {
                        Ex = ex
                    });
                }
            }
        }

        protected override void Construct(IUnitOfWork uow, CatalogSupplierCommentEntity entity)
        {
            base.Construct(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the catalog supplier comment.
    /// </summary>
    public class UpdateCatalogSupplierComment : UpdateComment<CatalogSupplierCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CatalogSupplierCommentFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out CatalogSupplierCommentEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdateCatalogSupplierStats
            {
                EntityID = result.HolderID
            });
        }

        protected override void Revise(IUnitOfWork uow, CatalogSupplierCommentEntity entity)
        {
            base.Revise(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the catalog supplier comment.
    /// </summary>
    public class DeleteCatalogSupplierComment : DeleteComment<CatalogSupplierCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow)
        {
            int holderID = uow.Execute(new GetCatalogSupplierComment
            {
                ThrowsException =  true,
                EntityID = EntityID
            }).Result.HolderID;

            base.Work(uow);

            uow.Execute(new UpdateCatalogSupplierStats
            {
                EntityID = holderID
            });
        }

        #endregion
    }

    /// <summary>
    /// Gets the catalog supplier comment.
    /// </summary>
    public class GetCatalogSupplierComment : GetComment<CatalogSupplierCommentEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over catalog supplier comment collection.
    /// </summary>
    public class SearchCatalogSupplierComments : SearchComments<CatalogSupplierCommentEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchCatalogSupplierComments()
        {
            SortDir = SortDirection.Ascending;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public CatalogSupplierCommentFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<CatalogSupplierCommentEntity> Build(IUnitOfWork uow, IQueryable<CatalogSupplierCommentEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => x.FlagsValue, (int)FlagMask);
            query = query.OrderBy(x => x.CreatedOn, SortDir);
            return query;
        }

        #endregion
    }

    #endregion

    #region __Notification__

    /// <summary>
    /// Enqueues a catalog supplier comment notification message.
    /// </summary>
    /// <remarks>
    /// Message template code: NCATSUPCMT
    /// Allowed tokens: [T:Recipient.EntityID], [T:Recipient.Guid], [T:Recipient.Email], [T:Recipient.Username],
    /// [T:CatalogSupplierComment.Supplier.EntityID], [T:CatalogSupplierComment.Supplier.RatingAverage],
    /// [T:CatalogSupplierComment.Supplier.CommentCount], [T:CatalogSupplierComment.Supplier.Name],
    /// [T:CatalogSupplierComment.Supplier.ShortDescription], [T:CatalogSupplierComment.Account.EntityID],
    /// [T:CatalogSupplierComment.Account.Username], [T:CatalogSupplierComment.Account.Email],
    /// [T:CatalogSupplierComment.Account.Guid], [T:CatalogSupplierComment.EntityID],
    /// [T:CatalogSupplierComment.RatingCount], [T:CatalogSupplierComment.Title], [T:CatalogSupplierComment.Text],
    /// [T:CatalogSupplierComment.CreatedOn]
    /// </remarks>
    public class EnqueueCatalogSupplierCommentNotification : Operation<MessageEntity>
    {
        #region Properties

        /// <summary>
        /// Gets or sets the comment identifier.
        /// </summary>
        public int CommentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the recipient account identifier.
        /// </summary>
        public int RecipientID
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out MessageEntity result)
        {
            var comment = uow.Execute(new GetCatalogSupplierComment
            {
                ThrowsException = true,
                EntityID = CommentID
            }).Result;
            var recipient = uow.Execute(new GetAccount
            {
                ThrowsException = true,
                EntityID = RecipientID
            }).Result;
            var usrLocale = recipient.LocalizationProfile;
            int utcOffset = usrLocale.TimeZone.UtcOffset;
            string dtFmt = usrLocale.Country.DateTimeFormat;
            var supplier = uow.Execute(new GetCatalogSupplier
            {
                ThrowsException = true,
                EntityID = comment.HolderID
            }).Result;
            var t_supplier = supplier.Translation(usrLocale.Language.EntityID);

            result = uow.Execute(new CreateTemplatedMessageByCode
            {
                TemplateCode = "NCATSUPCMT",
                LanguageID = usrLocale.Language.EntityID,
                Replacements = new Dictionary<String, String>
                {
                    {"Recipient.EntityID", recipient.EntityID.ToString()},
                    {"Recipient.Email", recipient.Email},
                    {"Recipient.Username", recipient.Username},
                    {"Recipient.Guid", recipient.Guid.ToString()},
                    {"CatalogSupplierComment.Supplier.EntityID", supplier.EntityID.ToString()},
                    {"CatalogSupplierComment.Supplier.RatingAverage", supplier.RatingAverage.ToString()},
                    {"CatalogSupplierComment.Supplier.RatingCount", supplier.RatingCount.ToString()},
                    {"CatalogSupplierComment.Supplier.CommentCount", supplier.CommentCount.ToString()},
                    {"CatalogSupplierComment.Supplier.Name", t_supplier != null 
                        ? t_supplier.Name 
                        : String.Empty},
                    {"CatalogSupplierComment.Supplier.ShortDescription", t_supplier != null 
                        ? t_supplier.ShortDescription 
                        : String.Empty},
                    {"CatalogSupplierComment.Account.EntityID", comment.Account != null 
                        ? comment.Account.EntityID.ToString() 
                        : String.Empty},
                    {"CatalogSupplierComment.Account.Username", comment.Account != null 
                        ? comment.Account.Username 
                        : String.Empty},
                    {"CatalogSupplierComment.Account.Email", comment.Account != null 
                        ? comment.Account.Email 
                        : String.Empty},
                    {"CatalogSupplierComment.Account.Guid", comment.Account != null 
                        ? comment.Account.Guid.ToString() 
                        : String.Empty},
                    {"CatalogSupplierComment.EntityID", comment.EntityID.ToString()},
                    {"CatalogSupplierComment.Title", comment.Title},
                    {"CatalogSupplierComment.Text", comment.Text},
                    {"CatalogSupplierComment.CreatedOn", comment.CreatedOn.ToLocal(utcOffset).ToStringByFmt(dtFmt)}
                },
                To = recipient.Email,
                Flags = MessageFlags.Active
            }).Result;
        }

        #endregion
    }

    #endregion
}
